﻿using System;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web;
using System.Web.Http.Filters;
using KL.UFrame.Core.Log;
using KL.UFrame.Core.Unity;
using Newtonsoft.Json;
using NLog;

namespace KL.UFrame.Core.Exception
{
    public class ApiExceptionFilterAttribute : ExceptionFilterAttribute
    {
        private ICommonLogger _logger;

        public ApiExceptionFilterAttribute()
        {
            _logger = UnityBootstrapper.Current.GetService<ICommonLogger>();
        }

        public ApiExceptionFilterAttribute(ICommonLogger logger)
        {
            _logger = logger;
        }
        private static HttpResponseMessage GetResponse(int code, string message,HttpStatusCode status= HttpStatusCode.BadRequest)
        {
            var resultModel = $"{{\"Code\":{code},\"Message\":\"{message}\"}}";
            return new HttpResponseMessage(status)
            {
                Content = new StringContent(resultModel,Encoding.UTF8, "application/json")
            };
        }

        public override void OnException(HttpActionExecutedContext actionExecutedContext)
        {
            if (actionExecutedContext.Exception.TargetSite.ReflectedType == typeof (System.IO.Path))
            {
                actionExecutedContext.Response = GetResponse(404, "您访问目标的不存在", HttpStatusCode.NotFound);
            }
            else
            {
                var exceptionType = actionExecutedContext.Exception.GetType();
                if (exceptionType == typeof (ResultException))
                {
                    var resultException = actionExecutedContext.Exception as ResultException;
                    actionExecutedContext.Response = resultException == null
                        ? GetResponse(-500, "服务暂时不可用，请稍后再试")
                        : resultException.ToRequestMessage();
                }
                else if (exceptionType == typeof (UnauthorizedAccessException))
                {
                    actionExecutedContext.Response = GetResponse(401, "您没有访问权限", HttpStatusCode.Forbidden);
                }
                else
                {
                    actionExecutedContext.Response = GetResponse(500, "服务暂时不可用，请稍后再试",
                        HttpStatusCode.InternalServerError);
                }
            }

            _logger.Error("Action_Error:" + actionExecutedContext.Response.StatusCode
                                + Environment.NewLine + "Controller:" + actionExecutedContext.ActionContext.ActionDescriptor.ControllerDescriptor.ControllerName
                                + Environment.NewLine + "Http Method:" + actionExecutedContext.ActionContext.ActionDescriptor.ActionName
                                + Environment.NewLine + "Params:" + JsonConvert.SerializeObject(actionExecutedContext.ActionContext.ActionArguments)
                                + Environment.NewLine + "User Name:" + HttpContext.Current?.User?.Identity.Name
                                + Environment.NewLine + "IP:" + HttpContext.Current?.Request.UserHostAddress
                 , actionExecutedContext.Exception);
        }
    }
}
